package com.hw.core.system.service;

import com.hw.core.system.controller.CourseController;
import com.hw.core.system.entity.Course;
import com.hw.core.system.entity.CourseType;
import com.hw.core.system.repository.CourseRepository;
import com.hw.core.system.repository.CourseTypeRepository;
import com.hw.core.util.PageModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Transactional(readOnly = true)//全部方法只读事务
@CacheConfig(cacheNames = "course")
public class CourseService {
    private static final Logger logger = LoggerFactory.getLogger( CourseService.class );
    @Autowired
    private CourseRepository courseRepository;


    @Cacheable(key = "#page+'page'")
    public Page<Course> findCanShowCourseFather(int page, int size) {
        PageRequest pageRequest = new PageRequest( page - 1, size );
        //显示状态为1的课程
        return courseRepository.findCourseByPIdIsNullAndStatusIs( 1, pageRequest );
    }


    @Cacheable(key = "#name+'&'+#page+'page'")
    public Page<Course> findCourseFatherByNameLike(int page, int size, String name) {
        PageRequest pageRequest = new PageRequest( page - 1, size );
        return courseRepository.findCourseByPIdIsNullAndNameLikeOrderByName( "%" + name + "%", pageRequest );
    }

    @Cacheable(key = "#id+'list'")
    public List<Course> findCourseByPId(Integer id) {
        List<Course> courseByPIdEquals = courseRepository.findCourseByPIdEqualsOrderByName( id );
        return courseByPIdEquals;
    }

    @Cacheable(key = "#id+'course'")
    public Course findCourseById(Integer id) {
        return courseRepository.findOne( id );
    }

    @CacheEvict(allEntries = true)
    @Transactional
    public Course add(Course course) {
        return courseRepository.save( course );
    }


    public List<Course> findCourseByCourseTypesIn(List<CourseType> courseTypes) {
        return courseRepository.findCourseByCourseTypesIn( courseTypes );
    }



    @Cacheable(key = "#page+'&'+#name+'page'")
    public PageModel<Object[]> findCourseFatherAndSon(Integer page, Integer size,String name) {
        PageModel<Object[]> pageModel=new PageModel<>();
        PageRequest pageRequest = new PageRequest( page - 1, size );
        if (name != null && name != "") {
            Page<Course> father = courseRepository.findCourseByPIdIsNullAndNameLikeOrderByName( "%" + name + "%",pageRequest );
            List<Object[]> fatherSon = new ArrayList<>();
            pageModel.setNumber( page-1 );
            pageModel.setNumberOfElements( size );
            pageModel.setTotalPages(father.getTotalPages()  );
            pageModel.setTotalElements( father.getTotalElements() );
            for (Course course : father) {
                Object[] obj = new Object[2];
                obj[0] = course;
                obj[1] = courseRepository.findCourseByPIdEqualsOrderByName( course.getId() );
                fatherSon.add( obj );
            }
            pageModel.setContent( fatherSon );

        }else {
            Page<Course> father = courseRepository.findCourseByPIdIsNullOrderByName(pageRequest);
            List<Object[]> fatherSon = new ArrayList<>();
            pageModel.setNumber( page-1 );
            pageModel.setNumberOfElements( size );
            pageModel.setTotalPages(father.getTotalPages()  );
            pageModel.setTotalElements( father.getTotalElements() );
            for (Course course : father) {
                Object[] obj = new Object[2];
                obj[0] = course;
                obj[1] = courseRepository.findCourseByPIdEqualsOrderByName( course.getId() );
                fatherSon.add( obj );
            }
            pageModel.setContent( fatherSon );

        }

        return pageModel;
    }

    @CacheEvict(allEntries = true)
    @Transactional
    public void updateText(Course course) {
        Course one = courseRepository.findOne( course.getId() );
        one.setText( course.getText() );
    }

    @CacheEvict(allEntries = true)
    @Transactional
    public void delete(Integer id) throws Exception {
        Course one = courseRepository.findOne( id );
        if (one.getPId() != null) {//说明是子类
            courseRepository.delete( id );
        } else {//父类判断无子可删
            List<Course> son = courseRepository.findCourseByPIdEqualsOrderByName( id );
            if (son.size() == 0) {
                courseRepository.delete( id );
            } else {
                throw new Exception( "该课程有下级目录，不能删除" );
            }
        }
    }

    @CacheEvict(allEntries = true)
    @Transactional
    public void updateName(Course course) {
        Course one = courseRepository.findOne( course.getId() );
        one.setName( course.getName() );
    }

    @CacheEvict(allEntries = true)
    @Transactional
    public void updateCourseTypesById(Integer id, String name, List<CourseType> courseTypes) {
        Course one = courseRepository.findOne( id );
        one.setName( name );
        one.setCourseTypes( courseTypes );
    }

    @CacheEvict(allEntries = true)
    @Transactional
    public void updateImg(Integer id, String img) {
        Course one = courseRepository.findOne( id );
        one.setImg( img );
    }

    @CacheEvict(allEntries = true)
    @Transactional
    public void updateStatus(Integer id, Integer status) {
        Course one = courseRepository.findOne( id );
        one.setStatus( status );
    }
}
